package com.ruoyi.framework.security.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @author Leron
 */
@Order
@Component
public class LoginUserFilter extends OncePerRequestFilter {

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Object principal = SecurityUtils.getAuthentication().getPrincipal();
        if (!(principal instanceof  String)) {
            JSONObject json = JSON.parseObject(JSON.toJSONString(principal));
            long id = json.getLongValue("id");
            SysUser sysUser = sysUserService.selectUserById(id);
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(sysUser, loginUser);
            loginUser.setUser(sysUser);
            Set<String> strings = permissionService.getMenuPermission(sysUser);
            loginUser.setPermissions(strings);
            String[] authority = permissionService.getRolePermission(sysUser).toArray(new String[0]);
            UsernamePasswordAuthenticationToken credentials = new UsernamePasswordAuthenticationToken(loginUser,null, AuthorityUtils.createAuthorityList(authority));
            credentials.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(credentials);
        }
        filterChain.doFilter(request,response);
    }
}
